package com.hison.courseselectionsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hison.courseselectionsystem.domain.Teacher;
import com.hison.courseselectionsystem.dto.LoginFormById;
import com.hison.courseselectionsystem.dto.UpdatePwd;
import com.hison.courseselectionsystem.service.TeacherService;
import com.hison.courseselectionsystem.mapper.TeacherMapper;
import com.hison.courseselectionsystem.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author hison
* @description 针对表【teacher】的数据库操作Service实现
* @createDate 2023-11-16 21:53:51
*/
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher>  implements TeacherService{

    @Resource
    private  TeacherMapper teacherMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注册
     * @param teacher
     * @return {@link Result}
     */
    @Override
    public Result register(Teacher teacher) {
        QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        //1.注册之前先判断当前用户是否已经存在
        if (teacher.getTeacherId() != null & teacher.getTeacherId() != "") {
            wrapper.eq("teacher_id", teacher.getTeacherId());
        }
        if (teacher.getName() != null & teacher.getName() != "") {
            wrapper.eq("name", teacher.getName());
        }
        Teacher teacher1 = teacherMapper.selectOne(wrapper);
        if (teacher1 != null) {
            return Result.fail("注册失败，用户已经存在");
        }
        int i = teacherMapper.insert(teacher);
        return i > 0 ? Result.ok("注册成功") : Result.fail("注册失败，请将信息补充完整");
    }

    /**
     * 登录
     * @param loginForm
     * @return {@link Result}
     */
    @Override
    public Result login(LoginFormById loginForm) {
        //1.根据学号和用户查找是否存在该用户
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", loginForm.getId());
        queryWrapper.eq("pwd", loginForm.getPwd());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if (teacher == null) {
            return Result.fail("用户不存在，请先注册");
        }
        //生成随机token
        String token = UUID.randomUUID().toString(true);
        //将token存入缓存
        String tokenKey = "token:login" + token;
        //7.3存储
        //将对象转为map集合
        Map<String, Object> userMap = BeanUtil.beanToMap(teacher, new HashMap<>(),
                //设置忽略空值
                CopyOptions.create().setIgnoreNullValue(true)
                        //将字段的值转为string类型
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置token有效期  30分钟   session过期时间
        stringRedisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    /**
     * 获取个人信息
     * @param teacherId
     * @return {@link Result}
     */
    @Override
    public Result getInfo(String teacherId) {
        Teacher teacherId1 = query().eq("teacher_id", teacherId).one();
        return Result.ok(teacherId1);
    }

    /**
     * 修改密码
     * @param updatePwd
     * @return {@link Result}
     */
    @Override
    public Result update(UpdatePwd updatePwd) {
        //先根据传入的参数获取用户信息，判断是否还存在
        String oldPwd = updatePwd.getOldPwd();
        String name = updatePwd.getName();
        String id = updatePwd.getId();
        Teacher teacher = query().eq("pwd", oldPwd).eq("name", name).eq("teacher_id", id).one();
        if (teacher == null) {
            return Result.fail("用户不存在，修改失败");
        }
        Map<String, String> map = new HashMap<>();
        map.put("teacher_id", id);
        map.put("pwd", updatePwd.getNewPwd());
        teacherMapper.updatepwd(map);
        return null;
    }



}
